package cn.xiaoliu.order.service.impl;

import cn.xiaoliu.basic.exception.BusinessException;
import cn.xiaoliu.basic.service.impl.BaseServiceImpl;
import cn.xiaoliu.basic.utils.CodeGenerateUtils;
import cn.xiaoliu.basic.utils.PageList;
import cn.xiaoliu.order.domain.AdoptOrder;
import cn.xiaoliu.order.domain.OrderAddress;
import cn.xiaoliu.order.domain.ProductOrder;
import cn.xiaoliu.order.mapper.AdoptOrderMapper;
import cn.xiaoliu.order.mapper.OrderAddressMapper;
import cn.xiaoliu.order.mapper.ProductOrderMapper;
import cn.xiaoliu.order.query.AdoptOrderQuery;
import cn.xiaoliu.order.service.IAdoptOrderService;
import cn.xiaoliu.org.domain.Employee;
import cn.xiaoliu.org.mapper.EmployeeMapper;
import cn.xiaoliu.pay.constants.AlipayConstants;
import cn.xiaoliu.pay.domain.PayBill;
import cn.xiaoliu.pay.mapper.PayBillMapper;
import cn.xiaoliu.pay.service.IPayBillService;
import cn.xiaoliu.pet.domain.Pet;
import cn.xiaoliu.pet.mapper.PetMapper;
import cn.xiaoliu.quartz.constant.JobConstants;
import cn.xiaoliu.quartz.service.IQuartzService;
import cn.xiaoliu.quartz.utils.QuartzJobInfo;
import cn.xiaoliu.user.domain.Logininfo;
import cn.xiaoliu.user.domain.User;
import cn.xiaoliu.user.domain.UserAddress;
import cn.xiaoliu.user.mapper.UserAddressMapper;
import cn.xiaoliu.user.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdoptOrderServiceImpl extends BaseServiceImpl<AdoptOrder> implements IAdoptOrderService {
    @Autowired
    private PetMapper petMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AdoptOrderMapper adoptOrderMapper;
    @Value("${order.last.pay.time}")//spring提供的el 为了获取配置文件中的值
    private Integer lastPayTime;
    @Autowired
    private UserAddressMapper userAddressMapper;
    @Autowired
    private OrderAddressMapper orderAddressMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private PayBillMapper payBillMapper;
    @Autowired
    private IPayBillService payBillService;
    @Autowired
    private IQuartzService quartzService;
    @Autowired
    private ProductOrderMapper productOrderMapper;

    @Override
    public String submit(Map<String, Object> params, Logininfo logininfo) {
        //获取前端传过来的值
        Integer serviceMethod = Integer.valueOf(params.get("service_method").toString());
        Long addressId = Long.valueOf(params.get("address_id").toString());
        Long payMethod = Long.valueOf(params.get("pay_method").toString());
        Long petId = Long.valueOf(params.get("pet_id").toString());
        //一.校验
        if (StringUtils.isEmpty(serviceMethod)
                || StringUtils.isEmpty(addressId)
                || StringUtils.isEmpty(payMethod)
                || StringUtils.isEmpty(petId)){
            throw new BusinessException("参数为空");
        }
        //二.业务
        Pet pet = petMapper.loadById(petId);
        //1.设置宠物下架，宠物下架时间
        pet.setState(0);
        pet.setOffsaletime(new Date());
        //2.生成领养订单
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        AdoptOrder order = initAdoptOrder(pet, user);
        order.setPaySn(CodeGenerateUtils.generateUnionPaySn());
        adoptOrderMapper.save(order);//这里要返回自增id

        //谁来领养
        //订单的收获地址t_order_address--->t_user_address
        UserAddress userAddress = userAddressMapper.loadById(addressId);
        OrderAddress orderAddress = initOrderAddress(order, userAddress);
        //3.保存订单
        orderAddressMapper.save(orderAddress);
        System.out.println("下单成功，您需要支付的金额是"+order.getPrice());

        //4.生成支付订单
        PayBill bill = initPayBill(payMethod, pet, user, order);
        payBillMapper.save(bill);//要返回自增主键


        //超时未支付自动取消，定时器
        QuartzJobInfo jobInfo = new QuartzJobInfo();
        String jobName = JobConstants.TIME_OUT_ADOPT_LAST_PAY + order.getId();
        jobInfo.setJobName(jobName);
        HashMap<String, Object> map = new HashMap<>();
        map.put("type",JobConstants.TIME_OUT_ADOPT_LAST_PAY );
        map.put("orderId",order.getId());
        jobInfo.setParams(map);
        jobInfo.setFireDate(order.getLastPayTime());
        quartzService.addJob(jobInfo);

        //接收响应返回给前端
        return payBillService.pay(bill);
    }

    private PayBill initPayBill(Long payMethod, Pet pet, User user, AdoptOrder order) {
        PayBill bill = new PayBill();
        bill.setDigest("[摘要]对"+pet.getName()+"收购的支付订单！");
        bill.setMoney(order.getPrice());
        bill.setUnionPaySn(order.getPaySn());
        bill.setState(1);
        bill.setLastPayTime(order.getLastPayTime());
        bill.setPayChannel(payMethod);
        bill.setBusinessType(AlipayConstants.BUSINESS_TYPE_ADOPT);
        bill.setBusinessKey(order.getId());
        bill.setUser_id(order.getUser_id());
        bill.setShop_id(order.getShop_id());
        bill.setNickName(user.getUsername());
        return bill;
    }

    //查询用户自己的订单
    @Override
    public PageList<AdoptOrder> queryUserOrder(AdoptOrderQuery query, Logininfo logininfo) {
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        query.setUserId(user.getId());
        return super.queryPage(query);
    }
    //查询平台管理员订单或者店铺订单
    @Override
    public PageList<AdoptOrder> queryAdmin(AdoptOrderQuery query, Logininfo logininfo) {
        Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
        if (employee.getShop_id()!=null){
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

        @Override
        public OrderAddress getOrderAdress(String unionPaySn) {
            PayBill payBill = payBillMapper.loadByUnionPaySn(unionPaySn);
            String sn = "";
            if (AlipayConstants.BUSINESS_TYPE_ADOPT.equals(payBill.getBusinessType())){
                AdoptOrder order = adoptOrderMapper.getOrderAdressByUnionPaySn(unionPaySn);
                sn = order.getOrderSn();
            }else if (AlipayConstants.BUSINESS_TYPE_PRODUCT.equals(payBill.getBusinessType())){
                ProductOrder order = productOrderMapper.getOrderAdressByUnionPaySn(unionPaySn);
                sn = order.getOrderSn();
            }
            return orderAddressMapper.getAdressBySn(sn);

        }
    //取消订单
    @Override
    public void cancelByQuartz(Long orderId) {
        AdoptOrder order = adoptOrderMapper.loadById(orderId);
        if (order != null){
            if (order.getState() == 0){//一定要是待支付才处理
                //@TODO 主动查询支付宝，查看是否存在支付
                order.setState(-1);//-1是取消
                adoptOrderMapper.update(order);
            }
        }
    }

    private OrderAddress initOrderAddress(AdoptOrder order, UserAddress userAddress) {
        OrderAddress orderAddress = new OrderAddress();
        BeanUtils.copyProperties(userAddress,orderAddress);
        orderAddress.setOrder_id(order.getId());
        orderAddress.setOrderSn(order.getOrderSn());
        return orderAddress;
    }

    private AdoptOrder initAdoptOrder(Pet pet, User user) {
        AdoptOrder order = new AdoptOrder();
        order.setDigest("[摘要]对"+pet.getName()+"收购订单！");
        order.setState(0);//待支付
        order.setPrice(pet.getSaleprice());
        String orderSn = CodeGenerateUtils.generateOrderSn(user.getId());
        order.setOrderSn(orderSn);//订单编号
        order.setPet_id(pet.getId());
        order.setUser_id(user.getId());
        order.setShop_id(pet.getShop_id());
        //设置最后支付时间
        order.setLastPayTime(new Date(System.currentTimeMillis()+lastPayTime));
        return order;
    }
}
